define(function(require, exports, module) {
	'use strict';
    
    
    $.widget('rk.wrSearchBoxCtrl', {
        searchBox: null,
        tableBox: null,
        _create: function() {
            var me = this;
            var elem = me.element;
        },
        _init: function() {
            var me = this;
            var elem = me.element;
            me.searchBox = $('#adv_search_box');

            me.tableBox = elem.find('table.adv_tiaojaon_table');
            me.searchBox.find('.adv_search_head > .close').click(function() {
                me.close();
            });
            me.searchBox.find('a.adv_search_btn').click(function() {
                me._doSearch();
            });
            me.searchBox.find('a.adv_search_concel').click(function() {
                me.close();
            });
            elem.find('input.start_date').datepicker({
                dateFormat: 'yy-mm-dd'
            });
            elem.find('input.end_date').datepicker({
                dateFormat: 'yy-mm-dd'
            });
        },
        _reset: function() {
            var me = this;
            var elem = me.element;
            elem.find('input').prop('checked', false);
            elem.find('tr[by="time-selector"]').hide();
            var firstday = moment().startOf('month').format('YYYY-MM-DD');
            var today = moment().format('YYYY-MM-DD');
            elem.find('input.start_date').val(firstday);
            elem.find('input.end_date').val(today);
            $('#reportUser').val('');
            me._search_clicked = false;
        },
        _updateBelongTypeId: function() {
            var me = this;
            var elem = me.element;
            var checkboxes = elem.find('input.daily_type');
            checkboxes.each(function() {
                var ipt = $(this);
                var typeText = ipt.attr('typeText');
                var belongTypeId = $('#wr-tab').wrTabCtrl('getBelongTypeId', typeText);
                ipt.attr('val', belongTypeId);
            });
        },
        _initFcbkautocomplete: function() {
            var me = this;
            var ul = $("#reportUser").next();
            //清空数据
            $("#reportUser").find('option').remove();
            if (ul.is('ul')) {
                ul.find('.bit-box').remove();
                return; //inited
            }
            $("#reportUser").fcbkcomplete({
                json_url: "/search/u.action?s=m&pageNo=1",
                addontab: true,
                maxitems: 30,
                height: 10,
                filter_selected: true,
                input_min_size: -1,
                width: 30,
                cache: false
            });
        },
        _initDepartTree: function() {
            var me = this;
            if ($('#reportDepartment').hasClass('ui-autocomplete-input')) {
                $('#reportDepartment').multitreeselector('val', ['BAD-DATA']); //清空数据
                return; //inited
            }
            $('#reportDepartment').multitreeselector({
                width: 250,
                source: '/json/crm_dimension/dim-tree.action?belongId=' + 25 + '&dimType=' + 1
            });
        },
        _hideFcbkautocomplete: function() {
            var me = this;
            me.tableBox.find('tr[by="reportUser"]').hide();
        },
        _hideDepartTree: function() {
            var me = this;
            me.tableBox.find('tr[by="reportDepartment"]').hide();
        },
        _showFcbkautocomplete: function() {
            var me = this;
            me._initFcbkautocomplete();
            me.tableBox.find('tr[by="reportUser"]').show();
        },
        _showDepartTree: function() {
            var me = this;
            me._initDepartTree();
            me.tableBox.find('tr[by="reportDepartment"]').show();
        },
        show: function() {
            var me = this;
            me._reset();
            me._updateBelongTypeId(); //get by TabCtrl
            me.searchBox.show();
            var viewtype = me.currentViewType;
            if (viewtype == 'mine') {
                me.tableBox.find('tr[by="reportUser"]').hide();
                me._hideFcbkautocomplete();
                me._hideDepartTree();
            } else {
                me._showFcbkautocomplete();
                if (viewtype == 'subordinate') {
                    me._showDepartTree();
                } else {
                    me._hideDepartTree();
                }
            }
        },
        close: function() {
            var me = this;
            me.searchBox.hide();
            $('#wr-list-status').hide();
            if (me._search_clicked) {
                $('#middle').wrPageCtrl('loadData');
            }
        },
        currentViewType: 'mine',
        setViewType: function(viewtype) {
            var me = this;
            me.currentViewType = viewtype;
        },
        //
        _getQueryData: function() {
            var me = this;
            var elem = me.element;
            var data = {
                viewType: "" //default, mark as search request for back-end
            };
            //reportTypes
            var reportTypes = [];
            var reportType_checkboxes = elem.find('input.daily_type');
            reportType_checkboxes.each(function() {
                var checkbox = $(this);
                if (checkbox.is(':checked')) reportTypes.push(checkbox.attr('val'));
            });
            reportTypes = reportTypes.join(',');
            if (reportTypes) data.reportTypes = reportTypes;
            //date
            var radio = elem.find('.daily_date:checked');
            var ms_range;
            if (radio.size() > 0) {
                ms_range = me._getMilliseconds(radio.attr('val'));
                if (!ms_range) return;
                data.startTime = ms_range.start;
                data.endTime = ms_range.end;
            }
            //status
            var status = [];
            var status_checkboxes = elem.find('input.daily_status');
            status_checkboxes.each(function() {
                var checkbox = $(this);
                if (checkbox.is(':checked')) status.push(checkbox.attr('val'));
            });
            status = status.join(',');
            if (status) data.reportStatus = status;
            //userIds
            var usersInput = $('#reportUser');
            if (me.tableBox.find('tr[by="reportUser"]').is(':visible') && usersInput.val()) {
                var vals = usersInput.val();
                data.userIds = vals.join(',');
            }
            //departments
            var departmentsInput = $('#reportDepartment');
            if (me.tableBox.find('tr[by="reportDepartment"]').is(':visible')) {
                var arr = $('#reportDepartment').multitreeselector("val");
                if (arr && arr.length > 0) {
                    var vals = [];
                    for (var i = 0, len = arr.length; i < len; i++) {
                        var o = arr[i];
                        vals.push(o.value);
                    }
                    data.departIds = vals.join(',')
                }
            }

            return data;
        },
        _getMilliseconds: function(dateType) {
            var me = this;
            var elem = me.element;
            var range = {};
            switch (dateType) {
                case 'thisweek':
                    var mon = moment().startOf('isoWeek');
                    var sun = moment(mon);
                    sun.add(7, 'day');
                    //__alert( mon.format()+','+sun.format() );
                    range.start = mon.unix() * 1000;
                    range.end = sun.unix() * 1000;
                    break;
                case 'lastweek':
                    var mon = moment().startOf('isoWeek');
                    mon.subtract(7, 'days');
                    var sun = moment(mon);
                    sun.add(7, 'day');
                    //__alert( mon.format()+','+sun.format() );
                    range.start = mon.unix() * 1000;
                    range.end = sun.unix() * 1000;
                    break;
                case 'thismonth':
                    var firstday = moment().startOf('month');
                    var lastday = moment(firstday);
                    lastday.add(1, 'month');
                    //__alert( firstday.format()+','+lastday.format() );
                    range.start = firstday.unix() * 1000;
                    range.end = lastday.unix() * 1000;
                    break;
                case 'lastmonth':
                    var firstday = moment().startOf('month');
                    firstday.subtract(1, 'month');
                    var lastday = moment(firstday);
                    lastday.add(1, 'month');
                    //__alert( firstday.format()+','+lastday.format() );
                    range.start = firstday.unix() * 1000;
                    range.end = lastday.unix() * 1000;
                    break;
                case 'others':
                    var startInput = elem.find('input.start_date');
                    var endInput = elem.find('input.end_date');
                    var start = moment(startInput.val());
                    var end = moment(endInput.val());
                    //__alert( start.format()+','+end.format() );
                    if (end.isBefore(start)) {
                    } else {
                        range.start = start.unix() * 1000;
                        range.end = end.unix() * 1000;
                    }
                    break;
                default:
            }

            if (range.start && range.end)
                return range;
        },
        _search_clicked: false,
        _doSearch: function() {
            var me = this;
            var elem = me.element;
            var data = me._getQueryData();

            if (!data) return;
            var newData = {};
            newData['search.viewType'] = '';
            for (key in data) {
                var val = data[key];
                if (val && typeof val != 'function') {
                    newData['search.' + key] = val;
                }
            }

            rk.log(data);
            rk.oa.popupContent(function() {

            });
            // $('#taskDetailDiv').wrDetailCtrl('clean');
            // $('#wr-list-status').find('.number').html(0);
            // $('#wr-list-status').show();
            // me._search_clicked = true;
            // $('#middle').wrPageCtrl('loadData', {
            //     queryData: newData
            // });
        }
    });
})
